Skip to content

fix(command): 流截断不再冷却账号 / keep accounts routable on a truncated stream - #637

Open
BrianBoyCN wants to merge 3 commits into
caigee-cmd:mainfrom
BrianBoyCN:fix/command-stream-truncation
Open

BrianBoyCN wants to merge 3 commits into
caigee-cmd:mainfrom
BrianBoyCN:fix/command-stream-truncation

Conversation

@BrianBoyCN

Copy link
Copy Markdown
Contributor

中文

问题现象

单账号 Command Code 路由上,长请求会周期性整体不可用。实测(2026-12-03,一个账号、1336 成功请求)当天 47 次失败里有 35 次是 all accounts are cooling down,而真正的截断只有 9 次——一次截断放大成约 4 次次级失败:

03:28:01 error  command code stream ended before a terminal event   40059ms   ← 触发
03:28:41 error  all accounts are cooling down                          0ms
03:28:43 error  all accounts are cooling down                          0ms
03:28:45 error  all accounts are cooling down                          0ms
03:28:47 error  all accounts are cooling down                          0ms
03:28:50 error  all accounts are cooling down                          1ms
03:28:55 error  all accounts are cooling down                          0ms
03:28:58 ok                                                          (冷却到期)

这 35 条次级失败的 error_kind/error_code 都是 rate_limit,客户端会按限流退避,而实际原因是「上游把答到一半的流切断了」——完全可重试,且与账号健康无关。

根因

/alpha/generate 是 NDJSON 流,终态事件是 finish-step / finish。适配层(internal/providers/command/rewrite.go 的 sseWriter.finish() 与 chat.go 的 aggregateResponse())在没见到终态时构造的是一个普通 unavailable 错误:

return newProviderError(502, "command code stream ended before a terminal event")

Classify() 落到 default 分支 → Cooldown = 15s。而 nextBackoffCooldown 有 30s 地板:

if next < backoffFloor { next = backoffFloor }   // backoffFloor = 30s

于是任何正数冷却都会被抬到 ≥30s,同类失败再指数退避。单账号路由上没有别的账号可以 failover,整个渠道被冻结。这与 internal/executor/error.go 里既有的传输层失败处理(Failover:false, Cooldown:0,理由正是「单账号路由下一次握手超时就会变成 all accounts are cooling down」)自相矛盾:「上游已收下请求、已经产出内容、中途被切断」比握手失败更说明账号是健康的,却反而被惩罚。

线上证据(request_stream_diagnostics):两次有诊断的截断分别是 upstream_status=200、sse_event_count=532 / bytes=122605 和 sse_event_count=19 / bytes=3713,saw_done=0、cancellation_source=upstream_stream_error。即上游正常建流、正常下发内容,然后在没有任何终态帧的情况下关闭。9 次截断的耗时全部 ≥37s,而当天成功请求 p90 是 37.3s —— 只有长尾请求会被切断。

修复

1. 给截断一个独立 code,并按 upstream_empty 的先例豁免冷却

internal/providers/command/errors.go 新增 newStreamTruncatedError,把截断从"通用 unavailable"里分出来,带 providers.CodeStreamTruncated。internal/executor/error.go 紧随既有的 upstream_empty 特例处理它:

if providerErr.Code == providers.CodeStreamTruncated {
	classified.Failover = true
	classified.Cooldown = 0     // 必须恰好 0:正数会被抬到 30s 地板
	classified.RetryAfter = 0
}

Failover 保持 true(多账号时仍换账号),Cooldown 为 0 让账号立即回到轮询池。这与 #288(upstream_empty 不冷却账号)是同一套模式、同一处代码,不新增策略分支。

2. 报错信息带上实际观测到的流形态

原来只有一句固定文案,无法区分「答到一半被切」和「上游什么都没产出就中断」。wire.go 里新增 streamStats(事件数、字节数、最后一个事件类型、是否出现过真实内容),随截断错误一起带出,例如:

command code stream ended before a terminal event (532 events, 122605 bytes, last type "message", content=true)

新增的诊断会写进请求日志,让下一次故障可以自证,而不是靠猜。不包含任何提示词或生成内容,只含计数与事件类型名。

测试

  • TestClassifyErrorStreamTruncatedNoCooldown — 截断 → Kind=unavailable、Failover=true、Cooldown=0、RetryAfter=0
  • TestStreamTruncationDoesNotCoolPool — 端到端:对唯一账号观测到截断后,DownUntil 仍为空、ModelDownUntil 为空、RetryAfter 为 0,即下一次 pick 能成功
  • TestStreamReadErrorPreservesTruncatedCode — 网关 StreamReadError 包装后 code 不丢(否则冷却会回归)
  • TestChatStreamTruncationSurfacesCode — 流式路径:部分内容已上线,pipe 错误仍带 upstream_stream_truncated
  • TestChatNonStreamTruncationReportsObservedShape — 非流式路径的观测形态与「不回显内容」断言
  • 既有的 TestClassifyErrorUpstreamEmptyNoCooldown 对照组(普通 unavailable 保留冷却)未改动,确认只有这两个特例被豁免

go test ./...、go test -race ./internal/providers/command/ ./internal/executor/、go vet ./...、gofmt、git diff --check、scripts/release-notes.py validate 全部通过。

范围与未做的事

  • 没有改通用 unavailable 的 15s 冷却,也没有动 backoffFloor。只对这一个 code 豁免。
  • 没有在适配层合成终态帧把截断伪装成成功。截断就是截断,客户端应当能重试。
  • 没有处理另外两个上游协议语义(见下),它们需要单独决定,不与本 PR 混在一起。

实测中发现、未包含在本 PR 的两处

  1. {"type":"abort"} 事件被忽略。 官方 command-code CLI(我反编译 1.93.4 / 1.94.0 的 dist/cli.mjs 核对)对 abort 是显式终态,抛 AbortError;而适配层 handle() 的 default: return nil 会吞掉它,于是「上游主动 abort」被误报成「流被截断」。02:18 那条只出 19 个事件就断的,很可能就是这种情况。要不要把 abort 单列成一个 finish_reason,需要先定语义。
  2. pause_turn 被当成功。 官方 CLI 见到 pause_turn 会带 continuation 重发(最多 5 次);适配层 normalizeFinishReason 把它归成 stop,等于把「这一轮没跑完」静默当正常结束。修它需要引入续接逻辑,属于新功能而非 bugfix。

这两点建议单独开 issue 讨论,需要的话我可以接着提。


English

Problem

On a single-account Command Code route the whole channel periodically went unavailable. Measured on 2026-12-03 (one account, 1336 successful requests): 35 of the day's 47 failures were all accounts are cooling down, while only 9 were actual stream truncations — roughly a 4x amplification from one cut stream.

03:28:01 error  command code stream ended before a terminal event   40059ms   <- trigger
03:28:41 error  all accounts are cooling down                          0ms
03:28:43 error  all accounts are cooling down                          0ms
... 5 more ...
03:28:58 ok                                                          (cooldown expired)

All 35 secondary failures logged error_kind/error_code = rate_limit, so clients back off as if throttled, when the actual cause — the upstream cutting a half-delivered stream — is retryable and says nothing about account health.

Root cause

/alpha/generate is an NDJSON stream whose terminal events are finish-step / finish. When no terminal event arrives, the adapter (sseWriter.finish() in internal/providers/command/rewrite.go and aggregateResponse() in chat.go) builds a generic unavailable error:

return newProviderError(502, "command code stream ended before a terminal event")

Classify() falls to its default branch → Cooldown = 15s. And nextBackoffCooldown has a 30s floor:

if next < backoffFloor { next = backoffFloor }   // backoffFloor = 30s

So any positive cooldown is lifted to ≥30s, with exponential backoff on repeats. With no second account to fail over to, the entire channel freezes. This contradicts the transport-failure handling already in internal/executor/error.go (Failover:false, Cooldown:0, whose comment is literally that a single handshake timeout turns into "all accounts are cooling down" for every following request): a stream the upstream accepted, started serving, and then cut is more evidence the account is healthy than a failed handshake, yet it was the one being punished.

Wire evidence (request_stream_diagnostics): the two truncations with diagnostics showed upstream_status=200 with sse_event_count=532 / bytes=122605 and sse_event_count=19 / bytes=3713, saw_done=0, cancellation_source=upstream_stream_error. The upstream opened the stream, delivered content, then closed without any terminal frame. All nine truncations took ≥37s against a same-day p90 of 37.3s — only long-tail requests get cut.

Fix

1. Give the cut its own code and exempt it from cooldown, following the upstream_empty precedent. newStreamTruncatedError in internal/providers/command/errors.go marks the cut with providers.CodeStreamTruncated; internal/executor/error.go handles it next to the existing upstream_empty case:

if providerErr.Code == providers.CodeStreamTruncated {
	classified.Failover = true
	classified.Cooldown = 0     // must be exactly 0: any positive value hits the 30s floor
	classified.RetryAfter = 0
}

Failover stays true (multi-account routes still move on), Cooldown 0 returns the account to the rotation immediately. Same pattern, same place as #288 — no new policy branch.

2. Report the observed stream shape. The old message was a constant, so a cut answer could not be told apart from an upstream that aborted before producing anything. streamStats in wire.go records event count, bytes, last event type, and whether real content arrived:

command code stream ended before a terminal event (532 events, 122605 bytes, last type "message", content=true)

It lands in the request log so the next incident explains itself. No prompt or completion text is included — counters and event type names only.

Tests

  • TestClassifyErrorStreamTruncatedNoCooldown — Kind=unavailable, Failover=true, Cooldown=0, RetryAfter=0
  • TestStreamTruncationDoesNotCoolPool — end to end on the only account: DownUntil stays zero, ModelDownUntil empty, RetryAfter 0, so the next pick succeeds
  • TestStreamReadErrorPreservesTruncatedCode — the code survives the gateway's StreamReadError wrapper (otherwise the cooldown regresses)
  • TestChatStreamTruncationSurfacesCode — streaming path: partial content is on the wire and the pipe error still carries upstream_stream_truncated
  • TestChatNonStreamTruncationReportsObservedShape — observed shape plus "does not echo streamed content"
  • The existing TestClassifyErrorUpstreamEmptyNoCooldown control case (generic unavailable keeps its cooldown) is untouched, proving only these two codes are exempted

go test ./..., go test -race ./internal/providers/command/ ./internal/executor/, go vet ./..., gofmt, git diff --check, and scripts/release-notes.py validate all pass.

Scope

  • Generic unavailable keeps its 15s cooldown; backoffFloor is untouched. Only this one code is exempted.
  • No synthesized terminal frame to disguise a cut as success. A cut is a cut; the client should retry.
  • The two upstream protocol semantics below are deliberately not here; they need decisions of their own.

Found while measuring, not in this PR

  1. {"type":"abort"} is ignored. The official command-code CLI (I decompiled dist/cli.mjs for 1.93.4 and 1.94.0) treats abort as an explicit terminal (AbortError); the adapter's default: return nil swallows it, so an upstream-initiated abort is misreported as a truncation. The 02:18 request that ended after 19 events is likely this case. Giving abort its own finish_reason needs a semantic decision first.
  2. pause_turn is reported as success. The official CLI re-sends with a continuation (up to 5 attempts); normalizeFinishReason maps it to stop, silently treating an unfinished turn as complete. Fixing it means adding continuation logic — a feature, not a bugfix.

Both deserve their own issue; happy to file them.

A Command Code stream that the upstream cut after delivering content was
classified as a generic `unavailable` error, which applies a 15s cooldown that
`nextBackoffCooldown` lifts to the 30s floor on repeat failures. On a
single-account route that turns one truncated answer into a burst of
"all accounts are cooling down" failures, and the client reads them as rate
limiting rather than as a retryable upstream cut.

Report the cut with a distinct `upstream_stream_truncated` code and, following
the `upstream_empty` precedent, keep the account routable (failover, cooldown 0,
retry-after 0). Also carry the observed stream shape in the message so a cut
answer can be told apart from an upstream that aborted before producing
anything; no prompt or completion text is included.

Gated behind:
- go test ./... / -race on command+executor / go vet ./... / gofmt
- scripts/release-notes.py validate

@caigee-cmd caigee-cmd left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

感谢 @BrianBoyCN 这么细致的排查,线上数据和根因分析都很清楚,upstream_empty 同款的豁免思路我也认同,方向没问题 👍

合并前有几处小问题想麻烦再调整一下:

  1. bytesRead 从来没有被累加(internal/providers/command/wire.go)。streamStats.bytesRead 只在声明和 describe() 里出现,streamEventsObserved 没有给它加过值,所以错误信息里永远是 0 bytes。PR 描述里的 122605 bytes 来自 request_stream_diagnostics,不是这段代码产出的。建议在 readLine 之后 stats.bytesRead += len(line)(顺便加一条断言 bytes 非 0 的测试)。

  2. (*streamStats).observe 没被调用。streamEventsObserved 里把同样的逻辑内联写了一遍,留了一份死代码。直接在循环里调 stats.observe(event) 就好。

  3. TestChatNonStreamTruncationReportsObservedShape 的"不回显内容"断言是空断言。这个测试的流内容是 "Hel",却检查 message 里不含 "partial",无论实现如何都会通过。建议改成检查不含 "Hel"(或者把文本换成一个更独特的字符串)。

  4. TestClassifyErrorUpstreamEmptyNoCooldown 上的两行注释被删了,和本 PR 无关,麻烦恢复一下。

  5. (可讨论,不阻塞)newStreamTruncatedError 目前对所有"没有终态事件"的流都生效,包括一个事件都没收到就断开的情况;但常量注释和 changelog 写的是"delivered content and then ended"。要么在注释/changelog 里把范围说成"任何未见终态的流",要么只在 contentSeen 为 true 时才打这个 code,二选一保持一致即可。

我检查了兼容性:只影响 Command Code 这一种失败的冷却和对外 error code(从兜底的 upstream_error 变成 upstream_stream_truncated),没有改通用 unavailable 冷却和 backoffFloor,也没有 schema 或公开接口改动,不算破坏性改动。

abort / pause_turn 那两点也很有价值,欢迎单独开 issue。改完我再看一下就合,辛苦了!

@caigee-cmd caigee-cmd left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个 PR 在 2026-12-03 13:30(上海时间)的审查意见之后,只合了几次 main,本身的代码提交还是 03554f20,上次提的问题都还在:

  1. internal/providers/command/wire.go:streamStats.bytesRead 仍然只在声明和 describe() 里出现,没有累加,错误信息里的字节数永远是 0。
  2. (*streamStats).observe 仍然没有被调用,streamEventsObserved 里把同样的逻辑内联写了一遍,是死代码。
  3. TestChatNonStreamTruncationReportsObservedShape 的流内容是 "Hel",却断言 message 不含 "partial",仍然是空断言。
  4. TestClassifyErrorUpstreamEmptyNoCooldown 上和本 PR 无关的两行注释仍然被删了。
  5. (可讨论)常量注释和 changelog 写的是“已下发内容后被切断”,但 newStreamTruncatedError 对所有没有终态事件的流都生效,包括一个事件都没收到就断开的情况,两边还没对齐。

方向没问题,上面 1–4 改完我再看。

BrianBoy added 2 commits December 5, 2026 10:49
- wire.go: count raw bytes via a counting reader so streamStats.bytesRead is
  actually accumulated (was always 0); call stats.observe() instead of the
  duplicated inline logic; drop the unused streamEvents wrapper.
- chat_test.go: make the no-content-echo assertion real (check for the actual
  streamed fragment) and assert bytesRead is non-zero.
- classify_test.go: restore the two comment lines above
  TestClassifyErrorUpstreamEmptyNoCooldown that were unrelated to this change.
- Align the code's actual scope (any stream without a terminal event, content
  or not) across tlserr.go, errors.go, and the changelog.
- executor/error.go: correct the cooldown-floor comment — nextBackoffCooldown's
  30s floor applies from the third consecutive same-kind failure, not to any
  positive cooldown.
@BrianBoyCN
BrianBoyCN force-pushed the fix/command-stream-truncation branch from 4b2d814 to 294edff Compare December 5, 2026 02:50
@BrianBoyCN

Copy link
Copy Markdown
Contributor Author

感谢再列一遍,5 条都已处理(e2ea1ae9):

  1. bytesRead 已累加:wire.go 加了一个 countingReader 包住原始 body,describe() 现在能报出真实的字节数;同时加了一条断言 bytesRead 非零的测试(之前实测确实是 0 bytes,感谢指出)。
  2. observe 已接线:循环里改为调用 stats.observe(event),删除了内联重复逻辑;顺带删掉了零调用的 streamEvents 包装函数。
  3. 空断言已修正:改为断言 message 不含实际下发的内容片段 "Hel",另补了 bytes 非零断言。
  4. 注释已恢复:TestClassifyErrorUpstreamEmptyNoCooldown 上那两行与本 PR 无关的注释已还原。
  5. 措辞已对齐:采用了「注释改为描述实际范围」的方案——tlserr.go 常量注释、newStreamTruncatedError 注释、changelog 统一为「任何未见终态事件的流(无论是否已下发内容)」。理由:用 contentSeen 收窄会把这批零事件截断重新扔回 15s 冷却,正好回到本 PR 要消灭的放大路径;流式路径首帧前的场景由 probeStreamBody 兜着(failover),非流式路径没有 probe,收窄会让行为按入口分叉。

另外把 executor/error.go 里「任何正数冷却都会被抬到 30s」的注释修准了:30s 地板实际从第 3 次同 kind 连续失败才生效(前两次 15s),线上那串次级失败 15s 就足以复现。

本地已过 go test ./... / -race / vet / gofmt / release-notes.py validate,并合入了 main(v0.8.6 changelog archive)。CI 在跑,麻烦再看一下 🙏

@caigee-cmd caigee-cmd left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

昨天提的 5 点都改到了:countingReader 已接上,bytesRead 会累加,循环改走 observe,测试也会拦住 0 bytes 和内容回显。措辞按「未见终态事件就不上冷却」对齐,说得通。CI 全绿,可以合。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants